package com.fang.algorithm.leecode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description TODO
 * @date 2022/5/6 3:52 下午
 **/
public class Test15_LongestConsecutive {
    public static void main(String[] args) {
        int[] nums = new int[]{9, 1, 4, 7, 3, -1, 0, 5, 8, -1, 6};
        int i = longestConsecutive(nums);
        System.out.println(i);
    }

    public static int longestConsecutive(int[] nums) {
        if (nums.length < 2) {
            return nums.length;
        }
        Map<Integer, Integer> map = new HashMap<>(16);
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        int ans = 0;
        for (int num : nums) {
            if (!map.containsKey(num)) {
               continue;
            }
            int curAns = 1, begin = num + 1;
            while (map.containsKey(begin)) {
                map.remove(begin);
                ++begin;
                ++curAns;
            }
            begin = num - 1;
            while (map.containsKey(begin)) {
                map.remove(begin);
                --begin;
                ++curAns;
            }
            ans = Math.max(ans, curAns);
        }
        return ans;
    }
}
